package com.imc.platform.base.user.security;

import com.imc.platform.base.menu.dao.repository.MenuRepository;
import com.imc.platform.base.menu.pojo.Menu;
import com.imc.platform.base.user.dao.repository.UserRepository;
import com.imc.platform.base.user.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by tanweiping on 2018/9/18.
 */
@Service
public class SSOAuthenticationManager implements AuthenticationManager {

    @Autowired
    UserRepository userRepository;
    @Autowired
    MenuRepository menuRepository;

    public Authentication authenticate(Authentication auth) throws AuthenticationException {
        Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
        User user = userRepository.findAllByLoginName(auth.getName());
        if (user != null) {
            Set<Menu> permissions = menuRepository.findAllByUserId(String.valueOf(user.getId()));
            for (Menu permission : permissions) {
                if (permission != null && permission.getMenuName() != null) {
                    GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(permission.getMenuName());
                    //1：此处将权限信息添加到 GrantedAuthority 对象中，在后面进行全权限验证时会使用GrantedAuthority 对象。
                    grantedAuthorities.add(grantedAuthority);
                }
            }
            return new UsernamePasswordAuthenticationToken(auth.getName(), user.getLoginPwd(), grantedAuthorities);
        }
        throw new BadCredentialsException("Bad Credentials");
    }
}